<?php

namespace app\h7_tool\controller\web\order;

use app\wc_card\facade\service\CardServiceFacade;
use app\wc_card\facade\service\MemberServiceFacade;
use app\wc_card\facade\service\OrderRechargeServiceFacade;
use app\wc_card\facade\service\OrderServiceFacade;
use xsframe\base\AdminBaseController;
use xsframe\util\ExcelUtil;
use xsframe\util\PriceUtil;
use think\facade\Db;

class Index extends AdminBaseController
{
    public function index()
    {
        $result = [];
        return $this->template('index', $result);
    }

    public function main($status = null)
    {
        $keyword = $this->params['keyword'] ?? '';
        $export  = $this->params['export'] ?? 0;

        $condition = [
            'o.uniacid' => $this->uniacid,
            'o.deleted' => 0,
        ];

        if (empty($starttime) || empty($endtime)) {
            $starttime = strtotime("-1 month");
            $endtime   = time();
        }

        $orderBy    = "createtime";
        $searchTime = trim($this->params["searchtime"]);
        if (!empty($searchTime) && is_array($this->params["time"]) && in_array($searchTime, array("create", "pay"))) {
            $starttime     = strtotime($this->params["time"]["start"]);
            $endtime       = strtotime($this->params["time"]["end"]);
            $condition[''] = Db::raw("o." . $searchTime . "time >= {$starttime} AND " . "o." . $searchTime . "time <= {$endtime} ");
            $orderBy       = $searchTime . "time";
        }

        $condition['o.service_type'] = 1;

        if (is_numeric($status)) {
            switch ($status) {
                case 0:
                    $condition['o.status'] = 0;
                    break;
                case 1:
                    $condition['o.status'] = 1;
                    break;
                case -1:
                    $condition['o.status'] = -1;
                    break;
            }
        }

        if (!empty($keyword)) {
            $str = " o.ordersn like '%" . trim($keyword) . "%' ";
            $str .= " or o.transaction_id like '%" . trim($keyword) . "%' ";
            $str .= " or or.recharge_name like '%" . trim($keyword) . "%' ";
            $str .= " or c.card_no like '%" . trim($keyword) . "%' ";
            $str .= " or m.mobile like '%" . trim($keyword) . "%' ";

            $condition[''] = Db::raw($str);
        }

        $field = "m.nickname,m.realname,m.mobile";
        $field .= ",or.recharge_name,or.recharge_id,or.recharge_desc,or.recharge_price,or.recharge_days,or.card_id";
        $field .= ",o.*";
        $field .= ",c.card_no";

        $list  = OrderServiceFacade::getDetailList($condition, $field, "{$orderBy} desc");
        $total = OrderServiceFacade::getDetailTotal($condition);
        $pager = pagination2($total, $this->pIndex, $this->pSize);

        $statusArr = array(
            -1 => array("css" => "default", "name" => "已关闭"),
            0  => array("css" => "danger", "name" => "待付款"),
            1  => array("css" => "success", "name" => "已付款"),
        );
        $paytype   = array(
            0 => array("css" => "default", "name" => "未支付"),
            1 => array("css" => "success", "name" => "微信支付"),
            // 2 => array("css" => "warning", "name" => "支付宝支付"),
            // 3 => array("css" => "danger", "name" => "余额支付"),
            // 4 => array("css" => "default", "name" => "后台付款"),
        );

        $totalMoney = 0.00;
        foreach ($list as &$value) {
            $value["statusvalue"]  = $value["status"];
            $value['paytypevalue'] = $value['paytype'];

            $value["statusname"] = $statusArr[$value["status"]]["name"];
            $value["statuscss"]  = $statusArr[$value["status"]]["css"];

            $value["paytypename"] = $paytype[$value["paytype"]]["name"];

            $totalMoney = $totalMoney + $value['price'];
        }
        unset($value);

        # 导出Excel数据
        if (!empty($export)) {
            $list = OrderServiceFacade::getDetailListAll($condition, $field, "{$orderBy} desc");
            if (!empty($list)) {
                foreach ($list as &$item) {
                    $item['createtime'] = date("Y-m-d H:i:s", $item['createtime']);
                    $item['mobile']     = $item['mobile'] . "\t";
                    $item['card_no']    = $item['card_no'] . "\t";

                    $item["statusname"]  = $statusArr[$item["status"]]["name"];
                    $item["paytypename"] = $paytype[$item["paytype"]]["name"];
                }
                unset($item);

                $this->exportExcelData($list);
            }
        }

        $result = [
            'list'       => $list,
            'paytype'    => $paytype,
            'pager'      => $pager,
            'total'      => $total,
            'totalMoney' => PriceUtil::numberFormat($totalMoney),
            'status'     => $status,
            'starttime'  => $starttime,
            'endtime'    => $endtime,
        ];

        return $this->template('list', $result);
    }

    private function exportExcelData($list)
    {
        $title    = '对账单' . "(" . date('Y-m-d') . ")";
        $column   = ['ID', '日期', '订单号', '卡号', '套餐类型', '金额', '支付状态', '支付方式', '用户ID', '手机号', '对账单号'];
        $setWidh  = ['15', '20', '30', '30', '20', '20', '20', '20', '20', '30', '30'];
        $keys     = ['id', 'createtime', 'ordersn', 'card_no', 'recharge_name', 'price', 'statusname', 'paytypename', 'mid', 'mobile', 'transaction_id'];
        $last     = [];
        $filename = $title;

        ExcelUtil::export($title, $column, $setWidh, $list, $keys, $last, $filename);
    }

    public function status0()
    {
        return $this->main(0);
    }

    public function status1()
    {
        return $this->main(1);
    }

    public function status_1()
    {
        return $this->main(-1);
    }

    public function ajaxOrder()
    {
        $day   = (int)$this->params['day'];
        $order = $this->selectOrderPrice($day);
        unset($order['list']);
        $allOrder = $this->selectOrderPrice($day, true);
        unset($allOrder['list']);
        $avg = $this->selectOrderPrice($day, true, true);
        unset($allOrder['list']);
        $orders = array('order_count' => $order['count'], 'order_price' => number_format($order['price'], 2), 'allorder_count' => $allOrder['count'], 'allorder_price' => number_format($allOrder['price'], 2), 'avg' => number_format($avg['avg'], 2));
        show_json(1, array('order' => $orders));
    }

    /**
     * ajax return 七日交易记录.近7日交易时间,交易金额,交易数量（不含今日）
     */
    public function ajaxTransaction()
    {
        $orderPrice  = $this->selectOrderPrice(7);
        $transaction = $this->selectTransaction($orderPrice['list'], 7);

        if (empty($transaction)) {
            $i = 7;

            while (1 <= $i) {
                $transaction['price'][date('Y-m-d', time() - $i * 3600 * 24)] = 0;
                $transaction['count'][date('Y-m-d', time() - $i * 3600 * 24)] = 0;
                --$i;
            }
        } else {
            foreach ($transaction['price'] as &$item) {
                $item = round($item, 2);
            }

            unset($item);
        }

        $allOrderPrice  = $this->selectOrderPrice(7, true);
        $allTransaction = $this->selectTransaction($allOrderPrice['list'], 7, true);

        if (empty($allTransaction)) {
            $i = 7;

            while (1 <= $i) {
                $allTransaction['price'][date('Y-m-d', time() - $i * 3600 * 24)] = 0;
                $allTransaction['count'][date('Y-m-d', time() - $i * 3600 * 24)] = 0;
                --$i;
            }
        } else {
            foreach ($allTransaction['price'] as &$item) {
                $item = round($item, 2);
            }

            unset($item);
        }

        echo json_encode(array('price_key' => array_keys($transaction['price']), 'price_value' => array_values($transaction['price']), 'count_value' => array_values($transaction['count']), 'allprice_value' => array_values($allTransaction['price']), 'allcount_value' => array_values($allTransaction['count'])));
    }

    /**
     * 查询订单金额
     * @param int $day 查询天数
     * @param bool $is_all 是否是全部订单
     * @param bool $is_avg 是否是查询付款平均数
     * @return array
     */
    private function selectOrderPrice($day = 0, $is_all = false, $is_avg = false)
    {
        $day = (int)$day;

        if ($day != 0) {
            if ($day == 30) {
                $yest        = date('Y-m-d');
                $createtime1 = strtotime(date('Y-m-d', strtotime('-30 day')));
                $createtime2 = strtotime($yest . ' 23:59:59');
            } else if ($day == 7) {
                $yest        = date('Y-m-d');
                $createtime1 = strtotime(date('Y-m-d', strtotime('-7 day')));
                $createtime2 = strtotime($yest . ' 23:59:59');
            } else {
                $yesterday   = strtotime('-1 day');
                $yy          = date('Y', $yesterday);
                $ym          = date('m', $yesterday);
                $yd          = date('d', $yesterday);
                $createtime1 = strtotime($yy . '-' . $ym . '-' . $yd . ' 00:00:00');
                $createtime2 = strtotime($yy . '-' . $ym . '-' . $yd . ' 23:59:59');
            }
        } else {
            $createtime1 = strtotime(date('Y-m-d', time()));
            $createtime2 = strtotime(date('Y-m-d', time())) + 3600 * 24 - 1;
        }

        $param = array(
            'uniacid' => $this->uniacid,
            'deleted' => 0,
            'status'  => Db::raw("> 0"),
        );
        $where = Db::raw(" (( status > 0 and (paytime between {$createtime1} and {$createtime2})) or ((createtime between {$createtime1} and {$createtime2} ) and status>=0 )) ");

        $time = 'paytime';
        if (!empty($is_all)) {
            $time  = 'createtime';
            $where = Db::raw(" createtime between {$createtime1} and {$createtime2}");
        }

        if (!empty($is_avg)) {
            $time  = 'paytime';
            $where = Db::raw(" (status >0 and (paytime between {$createtime1} and {$createtime2}))");
        }

        $param[''] = $where;
        $pdo_res   = OrderServiceFacade::getList($param, 'id,price,mid,' . $time);

        $price  = 0;
        $avg    = 0;
        $member = array();

        foreach ($pdo_res as $arr) {
            $price    += $arr['price'];
            $member[] = $arr['mid'];
        }

        if (!empty($is_avg)) {
            $member_num = count(array_unique($member));
            $avg        = empty($member_num) ? 0 : round($price / $member_num, 2);
        }

        $result = array('price' => $price, 'count' => count($pdo_res), 'avg' => $avg, 'list' => $pdo_res);
        return $result;
    }

    /**
     * 查询近七天交易记录
     * @param array $list 查询订单的记录
     * @param int $days 查询天数默认7
     * @param bool $is_all 是否是全部订单
     * @return array $transaction["price"] 七日 每日交易金额
     */
    private function selectTransaction(array $list, $days = 7, $is_all = false)
    {
        $transaction = array();
        $days        = (int)$days;

        if (!empty($list)) {
            $i = $days;

            while (1 <= $i) {
                $transaction['price'][date('Y-m-d', time() - $i * 3600 * 24)] = 0;
                $transaction['count'][date('Y-m-d', time() - $i * 3600 * 24)] = 0;
                --$i;
            }

            if (empty($is_all)) {
                foreach ($list as $key => $value) {
                    if (array_key_exists(date('Y-m-d', $value['paytime']), $transaction['price'])) {
                        $transaction['price'][date('Y-m-d', $value['paytime'])] += $value['price'];
                        $transaction['count'][date('Y-m-d', $value['paytime'])] += 1;
                    }
                }
            } else {
                foreach ($list as $key => $value) {
                    if (array_key_exists(date('Y-m-d', $value['createtime']), $transaction['price'])) {
                        $transaction['price'][date('Y-m-d', $value['createtime'])] += $value['price'];
                        $transaction['count'][date('Y-m-d', $value['createtime'])] += 1;
                    }
                }
            }

            return $transaction;
        }

        return array();
    }

    public function detail()
    {
        $id = intval($this->params['id']);

        $item = OrderServiceFacade::getInfo(['id' => $id]);

        $item['statusvalue']  = $item['status'];
        $item['paytypevalue'] = $item['paytype'];

        $orderRechargeInfo = OrderRechargeServiceFacade::getInfo(['orderid' => $item['id']]);

        $cardInfo = CardServiceFacade::getInfo(['id' => $orderRechargeInfo['card_id']]);

        $member = MemberServiceFacade::getInfo(['id' => $item['mid']]);

        $result = [
            'item'              => $item,
            'member'            => $member,
            'cardInfo'          => $cardInfo,
            'orderRechargeInfo' => $orderRechargeInfo,
        ];
        return $this->template('detail', $result);
    }
}
